const { VUE_APP_BASE_URL } = process.env;
import { rsaEncrypt } from '@/utils/security.js';
import utils from '@/utils/utils.js';

let aesKey = ''; // 声明全局 aes 密钥

/**
 * 上传文件:仅支持单文件上传
 */
function postFile(filePath, type) {
  aesKey = utils.getAesKey(32); // 每次匹配拦截 生成不同的 aes 密钥
  const isPath = typeof filePath === 'string';

  const systemInfo = uni.getSystemInfoSync();
  const token = uni.getStorageSync('tokenfro' + process.env.VUE_APP_PLATFORMID);
  const DeviceType = systemInfo.deviceType;
  const DeviceId = systemInfo.deviceId;
  const TerminalType = systemInfo.uniPlatform == 'web' ? 'h5' : 'android';
  const version = uni.getStorageSync('Version' + process.env.VUE_APP_PLATFORMID)
    ? uni.getStorageSync('Version' + process.env.VUE_APP_PLATFORMID)
    : plus.runtime.version;

  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url:
        `${VUE_APP_BASE_URL}/energy-all-fapi/appuser/basic/v1/upload?type=` +
        type,
      method: 'POST',
      filePath: isPath ? filePath : undefined,
      name: 'file',
      header: {
        Authorization: token ? token : aesKey,
        DeviceType: DeviceType,
        DeviceId: DeviceId,
        PlatformId: process.env.VUE_APP_PLATFORMID,
        RandomStr: rsaEncrypt(aesKey),
        Sign: aesKey,
        UserType: 'appuser',
        TimeStamp: new Date().getTime().toString(),
        TerminalType: TerminalType,
        Version: version,
      },
      success: ({ data }) => {
        try {
          resolve(JSON.parse(data));
        } catch (error) {
          reject(new Error('解析响应数据失败: ' + error.message));
        }
      },
      fail: reject,
    });
  });
}

export { postFile };
